package com.shm.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.Comment;
import com.ruoyi.common.core.domain.vo.CommentVo;
import com.shm.mapper.CommentMapper;
import com.shm.service.ICommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 17526
 * @description 针对表【comment(评论表)】的数据库操作Service实现
 * @createDate 2023-08-09 19:41:31
 */
@Service
public class ICommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
        implements ICommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<CommentVo> listCommentVoOfProduct(Long productId, Long userId) {
        return commentMapper.listCommentVoOfProduct(productId, userId);
    }

    /**
     * 将评论数据封装成树形结构
     *
     * @param commentVoList
     * @return
     */
    @Override
    public List<CommentVo> buildTree(List<CommentVo> commentVoList) {
        // 将所有父级评论过滤出来
        List<CommentVo> fatherList = commentVoList.stream().filter((item) -> {
            return item.getType() == 0;
        }).collect(Collectors.toList());
        commentVoList.removeAll(fatherList);
        // 为所有父级评论寻找孩子
        for (CommentVo father : fatherList) {
            father.setChildren(new ArrayList<>());
            this.searchSon(father.getId(), father.getUserNickName(), father.getChildren(), commentVoList);
        }
        return fatherList;
    }


    /**
     * 寻找孩子
     *
     * @param fatherId
     * @param children
     * @param commentVoList
     */
    private void searchSon(Long fatherId, String fatherNickName, List<CommentVo> children, List<CommentVo> commentVoList) {
        for (CommentVo commentVo : commentVoList) {
            if (commentVo.getItemId().equals(fatherId)) {
                commentVo.setToUserNickName(fatherNickName);
                children.add(commentVo);
                this.searchSon(commentVo.getId(), commentVo.getUserNickName(), children, commentVoList);
            }
        }
    }
}




